package com.zyw.security.shiro.web.realm;

import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.security.shiro.web.authc.tk.SmsAuthcToken;
import org.apache.shiro.authc.*;

/**
 * @author zhangyw
 * @date 2018/1/25 9:54
 */
public class SmsAuthRealm extends BasicAuthRealm {

    public SmsAuthRealm() {
        this.setName("sky_sso_sms_realm");
        this.setAuthenticationTokenClass(SmsAuthcToken.class);
    }

    public SmsAuthRealm(AuthService authService) {
        this();
        this.setAuthService(authService);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        SmsAuthcToken smsAuthcToken = (SmsAuthcToken) token;

        AuthInfo authInfo = getAuthService().getAuthInfo(smsAuthcToken.getPhone());

        if (authInfo == null) {
            throw new UnknownAccountException("账户不存在");
        }

        if (!getAuthService().validCredentials(smsAuthcToken.getPhone(), smsAuthcToken.getCode(), null)) {
            throw new IncorrectCredentialsException("验证码有误，请重新输入");
        }

        return new SimpleAuthenticationInfo(authInfo, smsAuthcToken.getCredentials(), getName());
    }

}
